import * as THREE from 'three'
import { MOUSE } from 'three'
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader'
// 导入控制器，轨道控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
// 导入模型解析器
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'

var scene, camera, renderer
class Base3d {
  constructor(dom, onfinsh) {
    this.clock = new THREE.Clock()
    this.mixer
    this.panzi
    this.model
    // this.onfinsh()
    console.log(onfinsh)
    // console.log(dom, 'window')
    renderer = new THREE.WebGLRenderer({ antialias: true }) //{开启抗锯齿}
    scene = new THREE.Scene()
    camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.25, 200)
    camera.position.set(-1.8, 0.6, 2.7) //设置相机位置
    // camera.lookAt(new THREE.Vector3(0, 0, 0)) //设置相机方向
    // camera.up = new THREE.Vector3(0, 1, 0) //设置相机的抬头
    // scene.background = new THREE.Color(0xbfe3dd)
    renderer.setPixelRatio(window.devicePixelRatio) //设置屏幕像素比
    renderer.setSize(window.innerWidth, window.innerHeight, true) //设置渲染尺寸大小
    // this.renderer.setSize(window.innerWidth, window.innerHeight, true)
    renderer.setPixelRatio(window.devicePixelRatio) //为了兼容高清屏幕
    //色调映射
    renderer.toneMapping = THREE.ACESFilmicToneMapping
    renderer.toneMappingExposure = 2 //曝光强度

    dom.appendChild(renderer.domElement)
    // new RGBELoader().setPath('./files/hdr/').load('000.hdr', (texture) => {
    //   texture.mapping = THREE.EquirectangularReflectionMapping
    //   scene.background = texture //背景
    //   scene.environment = texture //环境
    // })
    this.setEnvMap('000')

    renderer.clearColor()
    this.addMesh()
    // 控制器
    const controls = () => {
      // 初始化控制器
      // 初始orbitControls让相机跟着鼠标观察
      const orbitControls = new OrbitControls(camera, renderer.domElement)
      orbitControls.enableDamping = true
      // orbitControls.target = new THREE.Vector3(10, 0, 0)
      // orbitControls.autoRotate = true
      orbitControls.mouseButtons = {
        LEFT: MOUSE,
        MIDDLE: MOUSE.DOLLY,
        RIGHT: MOUSE.ROTATE
      }
      window.addEventListener('wheel', this.onMouseWheeel.bind(this))
    }
    controls()
    this.render()

    const animate = () => {
      // renderer.setAnimationLoop(render.bind(this))
      requestAnimationFrame(animate)
      // stats.update()
      // renderer.render(scene, camera)
      this.render()

      // this.renderer.render(this.scene, this.camera)
    }
    animate()
    //监听场景变化，调整渲染尺寸(绑定当前对象的this)
    window.addEventListener('resize', this.onWindwResize.bind(this))
  }

  render() {
    var delta = this.clock.getDelta()
    this.mixer && this.mixer.update(delta)
    renderer.render(scene, camera)
  }
  setEnvMap(hdr) {
    new RGBELoader().setPath('./files/hdr/').load(hdr + '.hdr', (texture) => {
      texture.mapping = THREE.EquirectangularReflectionMapping
      scene.background = texture
      scene.environment = texture
    })
  }
  setModel(modelName) {
    this.model && this.model.removeFromParent()

    return new Promise((resolve) => {
      const loader = new GLTFLoader().setPath('files/gltf/')
      loader.load(
        modelName,
        (gltf) => {
          // console.log(gltf)
          this.model = gltf.scene.children[0]
          if ('bag2.glb' == modelName && !this.panzi) {
            this.panzi = gltf.scene.children[5]
            //   this.scene.add(this.panzi);

            // 修改摄像头为模型摄像头
            camera = gltf.cameras[0]
            //   调用动画
            this.mixer = new THREE.AnimationMixer(gltf.scene.children[1]) //动画混合器
            this.animateAction = this.mixer.clipAction(gltf.animations[0])
            //   设置动画播放时长
            this.animateAction.setDuration(20).setLoop(THREE.LoopOnce)
            //   设置播放完成之后停止
            this.animateAction.clampWhenFinished = true
            //   播放动画
            // this.animateAction.play()

            //   设置灯光
            this.spotlight1 = gltf.scene.children[2].children[0]
            this.spotlight1.intensity = 1
            this.spotlight2 = gltf.scene.children[3].children[0]
            this.spotlight2.intensity = 1
            this.spotlight3 = gltf.scene.children[4].children[0]
            this.spotlight3.intensity = 1
          }
          scene.add(gltf.scene)
          // this.scene.add(this.model);
          resolve(this.modelName + '模型添加成功')
        },
        (e) => {
          //   console.log("模型加载进度");
          console.log(e, '模型加载进度')
          // this.progressFn(e)
        }
      )
    })
  }
  async addMesh() {
    this.setModel('bag2.glb')
    // let res = await this.setModel('bag2.glb')
    // this.onfinsh(res)
  }
  onWindwResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    renderer.render(scene, camera)
  }
  onMouseWheeel(e) {
    let timeScale = e.deltaY > 0 ? -1 : 1
    this.animateAction.setEffectiveTimeScale(timeScale)
    this.animateAction.paused = false
    this.animateAction.play()
    if (this.timeoutid) {
      clearTimeout(this.timeoutid)
    }
    this.timeoutid = setTimeout(() => {
      this.animateAction.halt(0.5)
    }, 300)
  }
}
export default Base3d
